var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var inviteuid = '';
var page = 1;
var loadingMore = false;
var hasMore = true;

var longTap = false;

var startX = 0;



Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    choosenum: 0,
    eatnum: 0,

    gouwucheData: [],
    totalSel: true,
    totalPrice: 0,
    youhuiPrice: 0, //优惠金额
    jisuanCount: 0,

    uid: 0,
    token: '',

    noData: false,

    delBtnWidth: 40,

    my_cion: 88,
    yunfei: 6,

    tuijian_data: [],
    goodsImgView_h: 160,

    colorSet: '',
    showjoin: false,
    membercard: '',

    phone: '853',//手机号
    code: '',//验证码
    codename: '获取验证码',

    areaArr: '',
    areaIndex: 0,
    areaSelected: '',


  },

  addressInfo: {},
  isLogin: false,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // var membercard = wx.getStorageSync('membercard');
    // that.setData({
    //   membercard : membercard
    // })
    hasMore = true;
    page = 1;

    var tc = app.get_tc();
    var titlename = tc == 1 ? '購物車' : '购物车';
    that.setData({
      choosenum: options.choosenum,
      eatnum: options.eatnum,
    });
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", this.data.choosenum);
    wx.setNavigationBarTitle({
      title: titlename,
    });


    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('gouwuche/gouwuche', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        tc: tc
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        goodsImgView_h: (res.windowWidth - 30) / 2;
        that.setData({
          isIphone_x: isIphone_x
        })
      }
    })

    this.getYunfeiSet();

    this.loadGoodsListData();
  },

  onShow: function () {
    this.getLoginInfo();
    var membercard = wx.getStorageSync('membercard');
    if (membercard) {
      this.isLogin = true;
    }

    startX = 0;
    
    var gwc_datas = wx.getStorageSync('gwc_datas');

    if (!gwc_datas) {
      gwc_datas = [];
    }
    var allSel = true;
    if (gwc_datas.length > 0) {
      var ghsid_0 = gwc_datas[0].ghsid;
      gwc_datas.forEach(function (m, i) {
        m.left = 0;
        if (m.ghsid != ghsid_0) {
          m.sel = false;
          allSel = false;
        }
      });
      console.log("gwc_datas==", gwc_datas);
      for (var i = 0; i < gwc_datas.length; i++) { //有特惠菜的情况加钱
        if (gwc_datas[i].sel) {
          if (gwc_datas[i].attribute) {
            var attribute = gwc_datas[i].attribute;
            for (var j = 0; j < attribute.length; j++) {
              if (!gwc_datas[i].jiaqian) {
                gwc_datas[i].jiaqian = 0;
              }
              if (attribute[j].attributePrice) {
                gwc_datas[i].jiaqian += parseInt(attribute[j].attributePrice);
              }
            }
          }
        }
      }
      this.setData({
        gouwucheData: gwc_datas,
        jisuanCount: gwc_datas.length,
        totalSel: allSel
      });
      this.calTotalPrice();
    } else {
      this.setData({
        gouwucheData: gwc_datas,
        jisuanCount: gwc_datas.length,
        totalSel: allSel
      });
    }
  },

  loadMore: function () {
    if (!loadingMore && hasMore) {
      loadingMore = true;
      page++;
    }
  },

  //全选／反选
  allSelected: function () {
    var allSel = !this.data.totalSel;
    var allData = this.data.gouwucheData;
    var ghsid_0 = allData[0].ghsid;
    for (var i = 0; i < allData.length; i++) {
      // if (allData[i].ghsid == ghsid_0) {
      //   allData[i].sel = allSel;
      // } else {
      allData[i].sel = allSel;
      // allSel = allSel;
      // }
    }
    this.setData({
      gouwucheData: allData,
      totalSel: allSel
    });
    this.calTotalPrice();
    this.resetAllDataLeft();
  },

  //选择商品动作
  selAction: function (e) {
    var index = e.currentTarget.dataset.index;
    var allData = this.data.gouwucheData;
    var ghsid_s = '';
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        ghsid_s = allData[i].ghsid;
        break;
      }
    }
    var selItem = allData[index];
    if (ghsid_s && !selItem.sel && selItem.ghsid != ghsid_s) {
      wx.showModal({
        title: '提示',
        content: '所选商品属不同商家，请分开结算',
        mask: 'true',
        showCancel: false
      })
    } else {
      selItem.sel = !selItem.sel;
    }
    var allsel = true;
    for (var i = 0; i < allData.length; i++) {
      if (!allData[i].sel) {
        allsel = false;
      } else {

      }
    }
    this.setData({
      gouwucheData: allData,
      totalSel: allsel
    });
    this.calTotalPrice();
  },

  //减少动作
  reduceAction: function (e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.gouwucheData;
    var newInputValue = allGwcData[index].buycount - 1
    if (newInputValue < 1) {
      return;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      gouwucheData: allGwcData
    })
    this.calTotalPrice();
    wx.setStorage({
      key: 'gwc_datas',
      data: allGwcData,
    })
  },
  //增加动作
  addAction: function (e) {
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.gouwucheData;
    var newInputValue = allGwcData[index].buycount + 1
    if (newInputValue > allGwcData[index].kucun) {
      var titlename = this.data.tc == 1 ? '超出庫存啦' : '超出库存啦';
      wx.showToast({
        title: titlename,
      });
      newInputValue = allGwcData[index].kucun;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      gouwucheData: allGwcData
    })
    this.calTotalPrice();
    wx.setStorage({
      key: 'gwc_datas',
      data: allGwcData,
    })
  },
  //输入框输入动作
  countInputAction: function (e) {
    var inputText = e.detail.value;
    if (!inputText) {
      return;
    }
    var index = e.currentTarget.dataset.itemid;
    var allGwcData = this.data.gouwucheData;
    var newInputValue = parseInt(inputText);
    if (newInputValue > allGwcData[index].kucun) {
      var titlename = this.data.tc == 1 ? '超出庫存啦' : '超出库存啦';
      wx.showToast({
        title: titlename,
      });
      newInputValue = allGwcData[index].kucun;
    }
    allGwcData[index].buycount = newInputValue;
    this.setData({
      gouwucheData: allGwcData
    })
    this.calTotalPrice();
    wx.setStorage({
      key: 'gwc_datas',
      data: allGwcData,
    })
  },

  //失去焦点时
  countInputBlur: function (e) {
    var inputText = e.detail.value;
    if (!inputText) {
      var index = e.currentTarget.dataset.itemid;
      var allGwcData = this.data.gouwucheData;
      var newInputValue = 1;
      allGwcData[index].buycount = newInputValue;
      this.setData({
        gouwucheData: allGwcData
      })
      this.calTotalPrice();
    }
  },

  //处理总价
  calTotalPrice: function () {
    var allData = this.data.gouwucheData;
    console.log("处理总价 allData===", allData);
    var allPrice = 0;
    var count = 0;
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        // if(allData[i].attribute){
        //   var attribute = allData[i].attribute;
        //   for(var j=0;j<attribute.length;j++){
        //     if(attribute[j].attributePrice){
        //       allPrice += parseInt(attribute[j].attributePrice) * 100;
        //     }
        //   }
        // }
        if (allData[i].selltype != '1') {
          if (this.data.membercard) {
            allPrice += allData[i].memberprice * allData[i].buycount;
          } else {
            allPrice += allData[i].price * allData[i].buycount;
          }
        }

        allPrice += parseInt(allData[i].yunfei) * 100;
        count++;
      }
    }
    this.setData({
      totalPrice: allPrice,
      youhuiPrice: 0,
      jisuanCount: count
    });
  },

  wxAuthFail: true,
  getLoginInfo: function () {
    var that = this;
    app.getLoginUserInfo(function (res) {
      console.log("啊啊啊啊", res);
      if (res && res != -1) {
        //更新数据
        that.wxAuthFail = false;
        if (res.chongzhi == 1) { //会员
          that.setData({
            membercard: true
          })
        } else {
          that.setData({
            membercard: ""
          })
        }
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.openid
        })
        that.userinfo = res;
      } else {
        that.wxAuthFail = true;
      }
    })
  },

  buyAction: function (e) {
    var that = this;
    if (that.wxAuthFail) {
      wx.login({
        success: function (e) {
          wx.setStorageSync('code', e.code);
        },
        fail: function (e) {
          console.log("wx.login fail:", e);
        }
      });
      wx.getUserProfile({
        desc: "下单需要",
        success: function (res) {
          console.log("用户已授权：", res);
          app.wxAuthRequest(res, function (res) {
            if (res != -1) {
              that.getLoginInfo();
            }
          });
        },
        fail: function (err) {
          console.log("wx.getUserInfo fail:", err);
        }
      })
    } else {
      if (this.isLogin) {
        that.buyActiontijiao();
      } else {
        var membercard = this.userinfo.mobile;
        console.log(membercard);
        if (!membercard) {
          wx.navigateTo({
            url: '/pages/join/join?',
          })
        } else {
          wx.navigateTo({
            url: '/pages/login/login?membercard=' + membercard,
          })
        }
      }
    }

  },


  buyActiontijiao: function () {
    // var membercard = wx.getStorageSync('membercard');
    // if (membercard) { //是否登录
      var allData = this.data.gouwucheData;
      var jiesuanArr = [];
      var choosenum = this.data.choosenum;
      var eatnum = this.data.eatnum;
      for (var i = 0; i < allData.length; i++) {
        if (allData[i].sel) {
          jiesuanArr = jiesuanArr.concat(allData[i]);
        }
      }
      if (jiesuanArr.length > 0) {
        var jieSuanStr = JSON.stringify(jiesuanArr);
        var url = "/pages/order-confirm/order-confirm?goodsArr=" + jieSuanStr + "&choosenum=" + choosenum + "&eatnum=" + eatnum;
        wx.navigateTo({
          url: url
        });
      } else {
        let title = this.data.tc == 1 ? '溫馨提示' : '温馨提示';
        let content = this.data.tc == 1 ? '請至少選擇壹件商品' : '请至少选择一件商品';
        wx.showModal({
          title: title,
          content: content,
          showCancel: false,
          success: function (res) {

          }
        })
      }
    // } else { //非会员
    //   if (this.userinfo && this.userinfo.membercard && this.userinfo.membercard.length > 2) {
    //     let mobile = this.userinfo.mobile;
    //     wx.navigateTo({
    //       url: '/pages/login/login?membercard=' + mobile,
    //     })
    //   } else {
    //     this.setData({
    //       showjoin: true
    //     })
    //   }
    // }

  },

  touchStart: function (e) {
    console.log("touchS" + e);
    //判断是否只有一个触摸点
    if (e.touches.length == 1) {
      //记录触摸起始位置的X坐标
      startX = e.touches[0].clientX
    }
  },
  touchMove: function (e) {
    console.log("touchM:" + e);
    var that = this
    if (e.touches.length == 1) {
      //记录触摸点位置的X坐标
      var moveX = e.touches[0].clientX;
      //计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = startX - moveX;
      //delBtnWidth 为右侧按钮区域的宽度
      var delBtnWidth = that.data.delBtnWidth;
      var txtStyle = 0;
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变

      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
        txtStyle = disX;
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = delBtnWidth;
        }
      }
      //获取手指触摸的是哪一个item
      var index = e.currentTarget.dataset.index;
      var list = that.data.gouwucheData;
      //将拼接好的样式设置到当前item中
      list[index].left = -txtStyle;
      //更新列表的状态
      this.setData({
        gouwucheData: list
      });
    }
  },
  touchEnd: function (e) {

    var that = this
    if (e.changedTouches.length == 1) {
      //手指移动结束后触摸点位置的X坐标
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = startX - endX;
      var delBtnWidth = that.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? delBtnWidth : 0;
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = that.data.gouwucheData;
      list[index].left = -txtStyle;

      //更新列表的状态
      that.setData({
        gouwucheData: list
      });

      console.log("touchEnd left = " + txtStyle + "; index = " + index, that.data.gouwucheData);
    }
  },

  resetAllDataLeft: function () {
    var allData = this.data.gouwucheData;
    for (var i = 0; i < allData.length; i++) {
      allData[i].left = 0;
    }
    this.setData({
      gouwucheData: allData,
    });
  },

  //空事件，阻止事件上传到父视图
  emtyAction: function () {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  itemLongTap: function (e) {
    longTap = true;
    var index = e.currentTarget.dataset.index;
    var that = this;
    var contentname = this.data.tc == 1 ? '從購物車中刪除？' : '从购物车中删除？';
    var confirmTextname = this.data.tc == 1 ? '確定' : '确定';
    wx.showModal({
      title: '提示',
      content: contentname,
      cancelText: '取消',
      confirmText: confirmTextname,
      success: function (res) {
        longTap = false;
        that.resetAllDataLeft();
        if (res.confirm) {
          var all_gwcDatas = that.data.gouwucheData;
          var new_gwcDatas = [];
          for (var i = 0; i < all_gwcDatas.length; i++) {
            if (i != index) {
              new_gwcDatas = new_gwcDatas.concat(all_gwcDatas[i]);
            }
          }
          that.setData({
            gouwucheData: new_gwcDatas,
          })
          wx.setStorageSync("gwc_datas", new_gwcDatas);
          that.calTotalPrice();
        }
      }
    })



  },

  itemBindTap: function (e) {
    if (!longTap) {
      this.resetAllDataLeft();
      this.goAtherPage(e);
    }
    longTap = false;
  },

  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    console.log(url)
    wx.redirectTo({
      url: url
    })
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({
          url: path
        });
      }
    }

  },

  //获取运费设置
  getYunfeiSet: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        if (!data.msg) {
          let myCion = parseInt(data[0].mianfei);
          let yunFei = parseInt(data[0].yunfei);
          that.setData({
            my_cion: myCion,
            yunfei: yunFei
          })
        }
      }
    });
  },


  loadGoodsListData: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      postuid: util.orgid,
      zhiding: 1,
      page: 1,
      num: 6
    };

    console.log("商品请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        if (!resData.msg) {
          //热销推荐
          that.setData({
            tuijian_data: resData
          })
        }
        wx.hideLoading();
      }
    });
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  attributeShow: function (e) {
    console.log('eeee', e.currentTarget.dataset.attr)
    if (!this.data.attributeShow) {
      this.setData({
        attributeShow: true,
        attribute: e.currentTarget.dataset.attr

      })
    } else {
      this.setData({
        attributeShow: false,
        attribute: e.currentTarget.dataset.attr
      })
    }
  },

  //判断商品是否有属性
  getAttribute: function (e) {
    console.log("e==", e);
    var that = this;

    var good = e.currentTarget.dataset.good;
    var goodKey = e.currentTarget.dataset.key;
    console.log("Good", e.currentTarget.dataset.good);
    console.log("addGoods", e.currentTarget.dataset.good.groupId);
    var group = e.currentTarget.dataset.good.groupId;
    if (group == 0) {
      that.addGoods(e);
    } else {
      that.showModal();
      var params = {
        publickey: util.publiccode,
        ac: "getAttribute",
        orgid: util.orgid,
        uid: that.data.uid,
        groupId: group
      };

      console.log("商品属性请求参数：", params);
      util.api({
        data: params,
        success: function (responseData) {
          console.log("商品属性:", responseData.data);
          var result = responseData.data;
          if (result.length > 0) {
            var groups = [];
            for (var i = 0; i < result.length; i++) {
              var exist = false;
              if (i == 0) {
                let groupObj = {
                  groupId: '',
                  groupName: "",
                  subList: []
                };
                groupObj.groupId = result[i].groupId;
                groupObj.groupName = result[i].groupName;
                let subObj = {};
                subObj.attributeId = result[i].attributeId;
                subObj.attributeName = result[i].attributeName;
                subObj.attributePrice = result[i].attributePrice;
                subObj.checked = false;
                subObj.counts = 0;
                groupObj.subList.push(subObj);
                groups.push(groupObj);
                continue
              } else {
                for (var j = 0; j < groups.length; j++) {
                  if (groups[j].groupId == result[i].groupId) {
                    let subObj = {};
                    subObj.attributeId = result[i].attributeId;
                    subObj.attributeName = result[i].attributeName;
                    subObj.attributePrice = result[i].attributePrice;
                    subObj.checked = false;
                    subObj.counts = 0;
                    groups[j].subList.push(subObj);
                    exist = true;
                    break
                  }
                }
                if (!exist) {
                  let groupObj = {
                    groupId: '',
                    groupName: "",
                    subList: []
                  };
                  groupObj.groupId = result[i].groupId;
                  groupObj.groupName = result[i].groupName;
                  let subObj = {};
                  subObj.attributeId = result[i].attributeId;
                  subObj.attributeName = result[i].attributeName;
                  subObj.attributePrice = result[i].attributePrice;
                  subObj.checked = false;
                  groupObj.subList.push(subObj);
                  groups.push(groupObj);
                }

              }


            }
            console.log('groups---->', groups);

            console.log('good---->', good);

            that.setData({
              mainfoodArray: [],
              drinksArray: [],
              discountfoodArray: [],
              attributeGroups: groups,
              // showAttributeNew: true,
              showAttribute: true,
              good: good,
              goodKey: goodKey
            });
            //已选择的优惠套餐
            for (var i = 0; i < good.attribute.length; i++) {
              if (good.attribute[i].groupId == '400') {
                that.data.discountfoodArray.push(good.attribute[i]);
                that.setData({
                  discountfoodArray: that.data.discountfoodArray,
                });
              }
            }
            that.markAttrGroups();
            // that.prefoodInitial();
          }
        }
      });
    };
  },




  radioChange: function (e) {
    var that = this
    console.log('radio发生change事件，携带value值为：', e.currentTarget.dataset)
    var Groups = this.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (Groups[i].groupId == e.currentTarget.dataset.groupid && Groups[i].subList[j].attributeId == e.currentTarget.dataset.value) {
          Groups[i].subList[j].checked = true;

          if (e.currentTarget.dataset.groupid == '400') {
            that.addDiscountfood(e)
          }
        } else if (Groups[i].groupId == e.currentTarget.dataset.groupid) {
          Groups[i].subList[j].checked = false
        }
      }

    }

    this.setData({
      attributeGroups: Groups,
    });


  },

  addDiscountfood(e) {
    var that = this;
    console.log('addDiscountfood', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var discountfoodArray = that.data.discountfoodArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;


          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          itemOb.attributePrice = Groups[i].subList[j].attributePrice;
          if (discountfoodArray.length < 1) {
            discountfoodArray.push(itemOb);

          } else {
            discountfoodArray.push(itemOb);
            discountfoodArray.splice(0, 1);
          }
        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('addDiscountfood', discountfoodArray)
    this.setData({
      attributeGroups: Groups,
      discountfoodArray: discountfoodArray
    });


  },


  hideAttribute: function () {
    this.hideModal()

  },

  delDiscountfood: function (e) {
    console.log('delDiscountfood', e.currentTarget.dataset);
    var that = this;
    var discountfoodArray = that.data.discountfoodArray;
    for (var i = 0; i < 1; i++) {
      if (i == e.currentTarget.dataset.idx) {
        discountfoodArray.splice(i, 1);
      }
    }
    console.log('DiscountfoodArray', discountfoodArray)
    this.setData({
      discountfoodArray: discountfoodArray
    });

  },

  addGoodsWithAttr(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);



    var that = this;
    var discountfoodArray = that.data.discountfoodArray;
    var mainfoodArray = that.data.mainfoodArray;
    var drinksArray = that.data.drinksArray;


    var gwc_datas = wx.getStorageSync('gwc_datas');
    console.log("gwc_datas ", gwc_datas);
    if (!gwc_datas) {
      gwc_datas = [];
    }

    var allSel = true;
    if (gwc_datas.length > 0) {
      var ghsid_0 = gwc_datas[0].ghsid;
      gwc_datas.forEach(function (m, i) {
        m.left = 0;
        if (m.ghsid != ghsid_0) {
          m.sel = false;
          allSel = false;
        }
      });
      console.log("gwc_datas[that.data.goodKey]1==", gwc_datas[that.data.goodKey]);
      var array = gwc_datas[that.data.goodKey].attribute;
      for (var i = 0; i < array.length; i++) {
        if (array[i].groupId == '400') {
          array.splice(i, 1);
        }
      }
      array = array.concat(discountfoodArray);
      array = array.concat(mainfoodArray);
      array = array.concat(drinksArray);

      gwc_datas[that.data.goodKey].attribute = array;
      console.log("gwc_datas[that.data.goodKey]2==", gwc_datas[that.data.goodKey]);
      for (var i = 0; i < gwc_datas.length; i++) { //有特惠菜的情况加钱
        if (gwc_datas[i].sel) {
          if (gwc_datas[i].attribute) {
            var attribute = gwc_datas[i].attribute;
            for (var j = 0; j < attribute.length; j++) {
              if (attribute[j].attributePrice) {
                gwc_datas[i].jiaqian += '+$' + attribute[j].attributePrice;
              } else {
                gwc_datas[i].jiaqian += '';
              }
            }
          }
        }
      }

      wx.setStorageSync('gwc_datas', gwc_datas);
      that.setData({
        gouwucheData: gwc_datas,
        jisuanCount: gwc_datas.length,
        totalSel: allSel
      });

      that.calTotalPrice();
    }

    if (this.data.showAttribute == true) {
      that.hideModal();
    }
    if (discountfoodArray.length == 1) {
      var contentname = that.data.tc == 1 ? '已添加特惠菜色' + discountfoodArray[0].attributeName : '已添加特惠菜色' + discountfoodArray[0].attributeName;
      wx.showToast({
        title: contentname,
      })
    } else if (discountfoodArray.length == 0) {
      var contentname = that.data.tc == 1 ? '未添加特惠菜色' : '未添加特惠菜色';
      wx.showToast({
        title: contentname,
      })
    }
    //  that.addGoods();

  },


  markAttrGroups: function () {
    var that = this;
    var Groups = that.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        let title = Groups[i].subList[j].attributeName
        if (title.indexOf("|") > 0) {
          let Arr = title.split('|')
          Groups[i].subList[j].attributeName = Arr[0]
          Groups[i].subList[j].mark = Arr[1];
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
          console.log('markAttrGroups', Groups[i].subList[j].mark)
        } else {
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
        }
      }


    }
    that.setData({
      attributeGroups: Groups
    })
  },


  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showAttribute: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showAttribute: true
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showAttribute: false
      })
    }.bind(this), 200)
  },

  //取消按钮
  quxiao: function () {
    console.log("quxiao");
    this.setData({
      showjoin: false
    })
  },

  //填写资料提交
  joinSubmit: function (e) {
    var that = this;
    var realname = e.detail.value.name;
    var mobile = e.detail.value.mobile;
    var diqu = that.data.areaArr[e.detail.value.diqu].area;
    var daolu = e.detail.value.daolu;
    var dasha = e.detail.value.dasha;
    var password = e.detail.value.password;
    var code = e.detail.value.code;
    console.log(e);
    if (!realname) {
      // app.dialog(that.data.tc == 1 ? '請填寫姓名' : '请填写姓名', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫姓名' : '请填写姓名',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }
    if (!mobile) {
      // app.dialog(that.data.tc == 1 ? '請填寫電話' : '请填写电话', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫電話' : '请填写电话',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }

    if (!diqu) {
      // app.dialog(that.data.tc == 1 ? '請填寫地區' : '请填写地区', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫地區' : '请填写地区',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }
    if (!daolu) {
      // app.dialog(that.data.tc == 1 ? '請填寫道路' : '请填写道路', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫道路' : '请填写道路',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }
    if (!dasha) {
      // app.dialog(that.data.tc == 1 ? '請填寫大廈' : '请填写大厦', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫大廈' : '请填写大厦',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }
    if (!password) {
      // app.dialog(that.data.tc == 1 ? '請填寫登錄密碼' : '请填写登录密码', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫登錄密碼' : '请填写登录密码',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }
    if (!code) {
      // app.dialog(that.data.tc == 1 ? '請填寫驗證碼' : '请填写验证码', 'loading');
      wx.showToast({
        title: that.data.tc == 1 ? '請填寫驗證碼' : '请填写验证码',
        icon: 'none',
        image: '/images/gth.png'
      })
      return;
    }

    that.addressInfo.name = realname;
    that.addressInfo.phone = mobile;
    that.addressInfo.address = diqu + daolu + dasha;


    var uid = that.data.uid;
    var token = that.data.token;
    console.log("uid = " + uid + "; token = " + token);


    var privatekey = utilMd5.hexMD5(uid + "checkaomensms" + token);
    var data = {
      "publickey": util.publiccode,
      "ac": "checkaomensms",
      "uid": uid,
      "privatekey": privatekey,
      "phone": mobile,
      "code": code,
    };


    util.actionSMS({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var resData = responseData.data;
        console.log(resData);
        if (resData.res == true) {


          var privatekey = utilMd5.hexMD5(uid + "bindhuiyuan" + token);
          var data = {
            "publickey": util.publiccode,
            "uid": uid,
            "ac": "bindhuiyuan",
            "privatekey": privatekey,
            "realname": realname,
            "mobile": mobile,
            "phone": mobile,
            "address": diqu + daolu + dasha,
            "password": password,
          };

          console.log(" data:", data);

          util.api({
            data: data,
            method: 'POST',
            success: function (responseData) {
              var resData = responseData.data;
              console.log(resData);
              if (resData.res == true) {
                // wx.setStorageSync('membercard', resData.membercard);
                that.saveAddress();
                wx.showToast({
                  title: '註冊成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function () {
                      that.setData({
                        showjoin: false
                      });
                      wx.navigateTo({
                        url: '/pages/login/login?membercard=' + mobile,
                      })
                    }, 2000);
                  }
                })

              } else {
                wx.showModal({
                  title: '提示',
                  content: resData.msg,
                  showCancel: false,
                })
              }

            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: resData.msg,
            showCancel: false,
          })
        }

      }
    });

  },

  saveAddress: function () {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": privatekey,
        "ac": "addaddress",
        "uid": that.data.uid,
        "name": that.addressInfo.name,
        "phone": that.addressInfo.phone,
        "address": that.addressInfo.address,
        "psd_phone": '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        console.log("保存地址成功");
      }
    });
  },

  getPhoneValue: function (e) {
    console.log(e);
    this.setData({
      phone: e.detail.value
    })
  },

  getCodeValue: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  getCode: function () {
    var that = this;
    console.log("shoujihao==", that.data.phone);
    var phone = that.data.phone;
    if (!phone) {
      app.dialog(that.data.tc == 1 ? '請填寫電話' : '请填写电话', 'loading');
      return;
    } else {
      that.setData({
        disabled: true
      })
      var privatekey = utilMd5.hexMD5(that.data.uid + "sendaomensms" + that.data.token);
      util.actionSMS({
        data: {
          "privatekey": privatekey,
          "ac": "sendaomensms",
          "uid": that.data.uid,
          "phone": that.data.phone,
        },
        method: "POST",
        success: function (responseData) {
          console.log(responseData)
          var resData = responseData.data;
          if (resData.res == true) {
            wx.showToast({
              title: that.data.tc == 1 ? '短信發送成功' : '短信发送成功',
              icon: 'success',
              duration: 1000
            })

            var num = 61;
            var timer = setInterval(function () {
              num--;
              if (num <= 0) {
                clearInterval(timer);
                that.setData({
                  codename: '重新发送',
                  disabled: false
                })

              } else {
                that.setData({
                  codename: num + "s"
                })
              }
            }, 1000)
          } else {
            wx.showModal({
              title: '提示',
              content: resData.msg,
              showCancel: false,
            })
          }

        }
      })

    }


  },

  //获取运费设置
  getYunfeiSet: function () {
    wx.showLoading({
      title: 'loading',
    });
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        wx.hideLoading();
        console.log("运费：", responseData);
        var data = responseData.data;
        if (data.res == undefined) {
          that.setData({
            areaArr: data,
            areaSelected: data[0]
          })
        }

      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //区域切换
  areaPicker: function (e) {
    let index = e.detail.value;
    let sel = this.data.areaArr[index];
    this.setData({
      areaIndex: index,
      areaSelected: sel
    });
  },




})